package ar.edu.isft189.controller;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import ar.edu.isft189.dao.MesaExamenCrudDao;
import ar.edu.isft189.model.AlumnoExamen;
import ar.edu.isft189.model.MesaExamen;

import com.google.gson.Gson;
import com.google.gson.JsonArray;
import com.google.gson.JsonElement;
import com.google.gson.reflect.TypeToken;

public class CRUDController extends HttpServlet {
	private static final long serialVersionUID = 1L;
	private MesaExamenCrudDao dao;

	public CRUDController() {
		dao = new MesaExamenCrudDao();
	}

	protected void doGet(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		
		System.out.println("Registro");

	}

	protected void doPost(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {

		if (request.getParameter("action") != null) {
			List<MesaExamen> lstMesas = new ArrayList<MesaExamen>();

			String action = (String) request.getParameter("action");
			Gson gson = new Gson();
			response.setContentType("application/json");

			// Obtengo todas las mesas de Examen habilitadas
			if (action.equals("listMesasExamen")) {
				try {
					// Obtengo la lista de Mesas
					lstMesas = dao.getAllMesas(null, "a.IDM ASC" );
					// Convert Java Object to Json
					JsonElement element = gson.toJsonTree(lstMesas,
							new TypeToken<List<MesaExamen>>() {
							}.getType());
					JsonArray jsonArray = element.getAsJsonArray();
					String listData = jsonArray.toString();
					// Return Json in the format required by jTable plugin
					listData = "{\"Result\":\"OK\",\"Records\":" + listData
							+ " ,\"TotalRecordCount\":" + lstMesas.size() + "}";
					System.out.println("Json " + listData);
					response.getWriter().print(listData);

				} catch (Exception ex) {
					String error = "{\"Result\":\"ERROR\",\"Message\":"
							+ ex.getMessage() + "}";
					response.getWriter().print(error);
					System.out.println("Json " + error);
					ex.printStackTrace();
				}
			}
			// Actualiza el folio y el Libro
			else if (action.equals("updateMesaExamen")) {
				MesaExamen me = new MesaExamen();

				int idm = request.getParameter("idm") != null ? Integer
						.parseInt(request.getParameter("idm")) : 0;
				String st = request.getParameter("estado") != null ? request
						.getParameter("estado").toString() : "A";
				int total = request.getParameter("cantExam") != null ? Integer
						.parseInt(request.getParameter("cantExam").toString())
						: 0;
				int aprob = request.getParameter("cantApr") != null ? Integer
						.parseInt(request.getParameter("cantApr").toString())
						: 0;
				int aus = request.getParameter("cantAus") != null ? Integer
						.parseInt(request.getParameter("cantAus").toString())
						: 0;

				me.setIdm(idm);
				me.setEstado(st);
				me.setCantExam(total);
				me.setCantAus(aus);
				me.setCantAprob(aprob);

				try {
					dao.updateMesaExamen(me);
					String listData = "{\"Result\":\"OK\"}";
					response.getWriter().print(listData);
				} catch (Exception ex) {
					String error = "{\"Result\":\"ERROR\",\"Message\":"
							+ ex.getStackTrace().toString() + "}";
					response.getWriter().print(error);
				}
			}
			// Accion de Actualizacion de notas de alumnos
			else if (action.equals("listStudents")) {

				try {
					int mesaId = Integer.parseInt(request.getParameter("idm")
							.toString());

					List<AlumnoExamen> lstAl = dao.getStudentsByIdm(mesaId);

					// Convert Java Object to Json
					JsonElement element = gson.toJsonTree(lstAl,
							new TypeToken<List<AlumnoExamen>>() {
							}.getType());
					JsonArray jsonArray = element.getAsJsonArray();
					String listData = jsonArray.toString();
					// Return Json in the format required by jTable plugin
					listData = "{\"Result\":\"OK\",\"Records\":" + listData
							+ " ,\"TotalRecordCount\":" + lstAl.size() + "}";
					System.out.println("Json " + listData);
					response.getWriter().print(listData);

				} catch (Exception ex) {
					String error = "{\"Result\":\"ERROR\",\"Message\":"
							+ ex.getMessage() + "}";
					response.getWriter().print(error);
					System.out.println("Json " + error);
					ex.printStackTrace();
				}

			} else if (action.equals("updateNotaAlumno")) {

				try {

					int mesaId = Integer.parseInt(request.getParameter("idm")
							.toString());
					int legajo = Integer.parseInt(request.getParameter(
							"legajoA").toString());
					int nota = Integer.parseInt(request.getParameter("nota")
							.toString());
					int codigoMe = Integer.parseInt(request.getParameter(
							"codigoMe").toString());

					AlumnoExamen ae = new AlumnoExamen();
					ae.setIdm(mesaId);
					ae.setLegajoA(legajo);
					ae.setNota(nota);
					ae.setCodigoMe(codigoMe);

					dao.updateNotaAlumno(ae);

					String listData = "{\"Result\":\"OK\"}";

					response.getWriter().print(listData);

				} catch (Exception ex) {
					String error = "{\"Result\":\"ERROR\",\"Message\":"
							+ ex.getMessage() + "}";
					response.getWriter().print(error);
					System.out.println("Json " + error);
					ex.printStackTrace();
				}

			}
		}
	}
}
